package com.medisign.sign.log.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

public class Base64Util {

    private static final Log log = LogFactory.getLog(Base64Util.class);

    /**
     * @param path
     * @return String
     * @description 将文件转base64字符串
     * @date 2018年3月20日
     * @author changyl
     * File转成编码成BASE64
     */

    public static String fileToBase64(String path) {
        if (StringUtils.isBlank(path)) {
            return "";
        }
        File source = new File(path);
        return fileToBase64(source);
    }

    public static String fileToBase64(File source) {
        String base64 = null;
        InputStream in = null;
        try {
            in = new FileInputStream(source);
            byte[] bytes = new byte[(int) source.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            log.error("文件转base64异常,错误信息为:{}", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

}
